<template>
  <div id="smartOptional" v-loading="loading">
    <div style="margin: 0 auto" class="main">
      <SelectProvinceNav :routeId="routeId" />
    </div>

    <el-scrollbar ref="scrollFun">
      <div class="main">
        <div class="subject-contaier">
          <div style="position: sticky; top: 0px; left: 0; z-index: 99">
            <!-- 智能头部 -->
            <subjectSelectHead
              v-if="ruleType != 3"
              :subjectSelectList="subjectSelectList"
              :isMajor="isMajor"
              :ruleType="ruleType"
              :combinedValues="combinedValues"
              :matchRateInfo="matchRateInfo"
              :zyMatchRate="zyMatchRate"
              :yxMatchRate="yxMatchRate"
              :xkType="xkType"
              @handleSelectResSave="handleSelectResSave"
              ref="colegeHeadRef"
            />
            <!-- 表格 -->
            <div
              style="height: 100%; overflow-anchor: none"
              ref="tableContainerRef"
            >
              <newSubjectMajor
                v-infinite-scroll="loadTableData"
                :infinite-scroll-disabled="isLastpage"
                :infinite-scroll-immediate="false"
                :yxTableData="yxTableData"
                :zyTableData="zyTableData"
                :subjectzyData="subjectzyData"
                :subjectyxData="subjectyxData"
                :isMajor="isMajor"
                :ruleType="ruleType"
                @updateIsMajor="updateIsMajor"
                @getEmitContact="getEmitContact"
              />
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
// 顶部选科方案组件
import SelectProvinceNav from '@/views/optional/components/SelectProvinceNav';
// 头部组件
import subjectSelectHead from '@/views/smartOptional/components/SubjectSelectHead';
// 表格组件
import newSubjectMajor from '@/views/smartOptional/components/NewSubjectMajor';
// 处理数据函数
import {
  updateSubjectData,
  transformData,
  transformToString,
  selectTable,
  getParams,
  fetchData,
  getCommonTableConfig,
  mapBestCombine,
  updateMatchRate,
  setStore,
  codeMp,
} from './components/utils';
import {
  // 获取院校table接口
  getSelectSearchSchool,
  // 获取专业table接口
  getSelectSearchMajorClass,
  // 获取选考科目表格数据
  getSelectSearchMajor,
  // 匹配率
  getSelectMatchContact,
  // 保存方案
  getSelectResSave,
  // 获取详情回显示
  getSelectResInfo,
} from '@/api/selectSubject/subject';

import { ref, onMounted, watch, computed, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { omit, get } from 'lodash';
const store = useStore();
const colegeHeadRef = ref(null);
const router = useRouter();
const route = useRoute();
// 是否为院校
const isMajor = ref(false);
// 左侧科目数据
const subjectSelectList = ref(store.getters.znxkInfo.subjectOptions);
// 计算属性，组合 selectCollegeList 和 selectMarjorList
const combinedValues = computed(() => ({
  selectCollegeList: store.getters.znxkInfo.selectCollegeList,
  selectMarjorList: store.getters.znxkInfo.selectMarjorList,
}));
// 列表+筛选
const loading = ref(false);
// 获取url接收的type
const ruleType = computed(() => route.query.type);
const routeId = ref(route.query.id);
// 院校表格数据
const yxTableData = ref([]);
const zyTableData = ref([]);
// 选考科目表格数据
const subjectyxData = ref([]);
const subjectzyData = ref([]);
// 专业表格数据
const page = ref(1);
// 是否为最后一页
const isLastpage = ref(false);
// 请求筛选的入参
const queryYxInfo = ref({});
const queryZyInfo = ref({});
// 匹配率数据
const matchRateInfo = ref({});
// 专业和院校的匹配率
const zyMatchRate = ref(0);
const yxMatchRate = ref(0);
const xkType = ref();
// 表格触底加载事件
const loadTableData = () => {
  if (isMajor.value && ruleType.value != 3) return;
  nextPage();
};
// 加载下一页
const nextPage = () => {
  page.value += 1;
  ruleType.value == 3 ? getRuleTypeList() : getTableList();
};

// 通用的获取表格数据函数
const fetchTableData = async (isMajor, api, additionalParams, targetData) => {
  loading.value = true;
  const { zySgID, yxSgID, sgId } = store.getters.znxkInfo;
  const sgid = (isMajor ? zySgID : yxSgID).length
    ? isMajor
      ? zySgID
      : yxSgID
    : sgId;
  // 构造请求参数
  const params = getParams(isMajor, additionalParams, {
    ...store.getters.znxkInfo.currentCityeInfo,
    ...store.getters.user.newSelectSubjectData,
    sgid,
    page,
  });

  // 调用通用的 fetchData 函数获取数据
  await fetchData(
    api,
    params,
    targetData,
    combinedValues,
    ruleType,
    isMajor,
    isLastpage,
  );
  loading.value = false;
};

// 表格数据
const getTableList = async () => {
  const api = isMajor.value ? getSelectSearchMajorClass : getSelectSearchSchool;
  const additionalParams = isMajor.value
    ? { code: queryZyInfo.value }
    : { ...queryYxInfo.value };

  // 调用通用函数获取表格数据
  await fetchTableData(
    isMajor.value,
    api,
    additionalParams,
    isMajor.value ? zyTableData : yxTableData,
  );
};

// 选考科目数据
const getRuleTypeList = async () => {
  const api = isMajor.value ? getSelectSearchMajor : getSelectSearchSchool;
  const additionalParams = isMajor.value
    ? { code: queryZyInfo.value, pageSize: 20 }
    : { ...queryYxInfo.value };

  // 调用通用函数获取选考科目数据
  await fetchTableData(
    isMajor.value,
    api,
    additionalParams,
    isMajor.value ? subjectzyData : subjectyxData,
  );
};

// 更新选项卡切换 - 是否切换的是院校或者专业
const updateIsMajor = (value) => {
  // 切换选项时重置表格配置
  resetTableConfig();
  isMajor.value = value;
  // 根据 `ruleType` 获取对应的列表数据
  ruleType.value == 3 ? getRuleTypeList() : getTableList();
  // 判断当前状态是否需要更新表格
  const { isManualSelect, tableSelectFlag, selectedIDs } =
    getCurrentConfig(value);
  // 如果已手动选择，或有选中项但未标记表格选择，则不更新表格
  if (isManualSelect || (selectedIDs.length && !tableSelectFlag)) return;

  // 根据当前 `isMajor` 设置选中列表并更新数据,获取当前选中的列表
  const selectedList = value
    ? combinedValues.value.selectMarjorList
    : combinedValues.value.selectCollegeList;

  // 计算 ID 出现的次数集合并更新科目数据的选择次数
  const newMap = mapBestCombine(selectedList);
  updateSubjectData(newMap, subjectSelectList.value);
};
// 判断当前状态是否需要更新表格
const getCurrentConfig = (value) => {
  const {
    isManualSelectYx,
    isManualSelectZy,
    zySgID,
    yxSgID,
    isTableSelectZy,
    isTableSelectYx,
  } = store.getters.znxkInfo;

  return {
    isManualSelect: value ? isManualSelectZy : isManualSelectYx,
    tableSelectFlag: value ? isTableSelectZy : isTableSelectYx,
    selectedIDs: value ? zySgID : yxSgID,
  };
};
// 重置表格配置page、专业和院校表格
const resetTableConfig = () => {
  page.value = 1;
  isLastpage.value = false;
  yxTableData.value = [];
  zyTableData.value = [];
  subjectyxData.value = [];
  subjectzyData.value = [];
};

// 保存方案
const handleSelectResSave = () => {
  // 如果没有选择院校或者专业无法保存
  const {
    selectCollegeList,
    selectMarjorList,
    zySgID,
    yxSgID,
    isManualSelectZy,
    isManualSelectYx,
    currentCityeInfo,
  } = store.getters.znxkInfo;
  if (!selectCollegeList.length && !selectMarjorList.length)
    return ElMessage.error('请选择院校或专业');

  let reqData = {
    pid: currentCityeInfo.provinceCode || store.getters.user.userInfo.pid,
    year: currentCityeInfo.year || localStorage.getItem('defultYear'),
    sgid: `${zySgID}|${yxSgID}`,
    infoText: JSON.stringify({
      yxList: selectCollegeList,
      zyList: selectMarjorList,
      isManualSelectZy,
      isManualSelectYx,
      year: currentCityeInfo.year,
    }),
    id: routeId.value || '', //存在为修改不存在为新增
    fromType: codeMp[ruleType.value],
    selectMore: null,
  };
  getSelectResSave(reqData).then((res) => {
    if (res.data.code == 20000) {
      routeId.value = res.data.data.id;
      localStorage.setItem('defultYear', currentCityeInfo.year);
      ElMessage({
        message: res.data.msg,
        type: 'success',
      });
      router.push('/mysubject');
    }
  });
};

// 传递出来获取匹配率
const getEmitContact = (val) => {
  getContact(val);
};
// 获取匹配率
const getContact = async (val) => {
  const { zySgID, yxSgID, currentCityeInfo } = store.getters.znxkInfo;
  const sgid = isMajor.value ? zySgID : yxSgID;
  if (sgid == '') return;
  const params = getCommonTableConfig({
    ...currentCityeInfo,
    ...store.getters.user.newSelectSubjectData,
    sgid,
    page,
  });
  if (val) params.sgid = val;
  const { data } = await getSelectMatchContact(params);
  matchRateInfo.value = data.data;
};
// 详情回显接口
const getDetail = async () => {
  try {
    // 获取数据
    const { data } = await getSelectResInfo({ id: routeId.value });
    if (data.code != 20000) return;
    // 解构数据并提供默认值
    const {
      pid: provinceCode,
      xk_type: rawXkType,
      province: provinceName,
      infoText = '',
      sgid = '',
    } = data.data;
    // 设置 `xk_type`，保持逻辑简单
    const xk_type = rawXkType === 2 ? 2 : 3;
    const year =
      infoText !== ''
        ? JSON.parse(infoText).year
        : localStorage.getItem('defultYear');
    // 解析 `infoText`，失败时返回空对象
    const zyList = get(JSON.parse(infoText || '{}'), 'zyList', []);
    const yxList = get(JSON.parse(infoText || '{}'), 'yxList', []);
    // 组装 `storeInfo`
    const storeInfo = {
      provinceCode,
      year,
      xk_type,
      provinceName,
    };
    // 更新 xkType 的值
    xkType.value = xk_type;

    // 处理 sgid 数据
    const result = sgid.split('|').map((str) => str.split(',').map(Number));

    // 更新 store 数据
    store.dispatch('znxk/updateManualSelect', {
      isMajor,
      flag: isMajor.value ? zyList : yxList,
    });
    setStore('znxk/changeZySgId', result[0] || [], true);
    setStore('znxk/changeYxSgId', result[1] || [], true);
    setStore('znxk/set_selectMarjorList', zyList);
    setStore('znxk/set_selectCollegeList', yxList);
    setStore('znxk/set_currentCityeInfo', storeInfo);
    setStore('user/set_newSelectSubjectData', storeInfo);
  } catch (error) {
    console.log('error:', error);
  }
};

// 监听院校或者专业已选择的item数组变化
watch(
  () => [
    combinedValues.value.selectCollegeList,
    combinedValues.value.selectMarjorList,
    isMajor.value
      ? store.getters.znxkInfo.zySgID
      : store.getters.znxkInfo.yxSgID,
  ],
  ([newCollegeList, newMajorList, sgId]) => {
    // 根据 isMajor 更新匹配率
    updateMatchRate(
      isMajor.value ? newMajorList : newCollegeList,
      sgId,
      isMajor.value ? zyMatchRate : yxMatchRate,
    );
    // 更新表格选择
    [zyTableData.value, yxTableData.value].forEach((table, i) =>
      selectTable(table, i == 0 ? newMajorList : newCollegeList),
    );
  },
  { deep: true },
);

// 根据选择的省份返回对应的科目
watch(
  () => store.getters.znxkInfo.subjectOptions,
  (newValue) => {
    subjectSelectList.value = newValue;
  },
  {
    deep: true,
  },
);
// 中间筛选条件和搜索框处理对应数据结构
watch(
  () => [
    store.getters.znxkInfo.filterCollegeList,
    store.getters.znxkInfo.filterMarjorList,
  ],
  ([yxnewVlaue, zynewVlaue]) => {
    resetTableConfig();
    const transformedYxInfo = transformData(yxnewVlaue);
    queryZyInfo.value = transformToString(zynewVlaue);
    queryYxInfo.value = {
      ...omit(transformedYxInfo, ['perfer']), // 去除 'perfer' 属性
      code: transformedYxInfo.perfer || '', // 设置 'code' 属性
    };
    ruleType.value == 3 ? getRuleTypeList() : getTableList();
  },
  { deep: true },
);
onMounted(async () => {
  if (routeId.value) {
    // 如果 routeId 存在，先执行 getDetail 再继续
    await getDetail();
  }

  // 默认请求院校 table 数据
  ruleType.value == 3 ? getRuleTypeList() : getTableList();

  // 获取匹配率
  getContact();
});

watchEffect(() => {
  if (!routeId.value) {
    xkType.value = store.getters.znxkInfo.currentCityeInfo.xk_type == 3 ? 3 : 2;
    setStore('znxk/changeYxSgId', [], true);
    setStore('znxk/changeZySgId', [], true);
    setStore('znxk/changeSelectMarjorList', [], true);
    setStore('znxk/changeSelectCollegeList', [], true);
  } else {
    // 路由 id 存在，详情回显
    getDetail();
  }
});
</script>

<style lang="scss" scoped>
#smartOptional {
  height: 100%;
  overflow: hidden;
  padding-bottom: 100px;
}
</style>
